package com.wzy.wzyblog.service;

import com.wzy.wzyblog.NotFoundException;
import com.wzy.wzyblog.dao.TypeRepository;
import com.wzy.wzyblog.po.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TypeServiceImpl implements TypeService{

    @Autowired
    private TypeRepository typeRepository;

//    增删改查分页放在在事务中
    @Transactional
    @Override
    public Type saveType(Type type) {
        return typeRepository.save(type);
    }

    @Transactional
    @Override
    public Type getType(Long id) {
        return typeRepository.findById(id).orElse(null);
    }

    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
            return typeRepository.findAll(pageable);

    }

    @Transactional
    @Override
    public void deleteType(Long id) {
        typeRepository.deleteById(id);

    }

    @Transactional
    @Override
    public Type updateType(Long id, Type type) {
//        查询对象
        Type t=typeRepository.findById(id).orElse(null);
//        没有查询到
        if (t==null){
//            抛出自定义异常
            throw new NotFoundException("不存在该类型");
        }
//        把查询的type 复制到 t上
        BeanUtils.copyProperties(type,t);
//        t中有id会完成更新
        return typeRepository.save(t);
    }
//      根据名字查询数据
    @Override
    public Type getTypeByName(String name) {
        return typeRepository.findByName(name);
    }

//查询所有数据
    @Override
    public List<Type> listType() {
        return typeRepository.findAll();
    }

    @Override
    public List<Type> listTypeTop(Integer size) {
//                        排序            按照降序             blog的多少
        Sort sort =Sort.by(Sort.Direction.DESC,"blogs.size");
//                                        指定size
        Pageable pageable =PageRequest.of(0,size,sort);
        return typeRepository.findTop(pageable);
    }


}
